#!/usr/bin/env python
# coding=utf-8
# Author:  vavava

__author__ = 'vavava'

def parse_argvs(argvs):
    """
    usage:
        from sys import argv
        argv_dic=vavava.util.parse_argvs(argv)
        if argv_dic:
            if argv_dic.get('-ids'):  userTokens=argv_dic.get('-ids').split('|')
            if argv_dic.get('-d'):  httpdebuglevel=argv_dic.get('-d')
            if argv_dic.get('-t'):  socket_timeout=argv_dic.get('-t')
    """
    if len(argvs)<=1:
        return
    argv_dic={}
    key=None
    for each in argvs:
        if each.find('-') == 0:
            key=each
        else:
            if key is not None:
                argv_dic[key]=each
                key=None
    if key is not None:
        argv_dic[key]=key
    return argv_dic

class LogAdapter(object):

    def __init__(self,log=None,mod_name="<undefine_module_name>"):
        self.LOG = log
        self.mod_name=mod_name
        if mod_name is None:
            self.mod_name="<undefine_module_name>"

    def info(self,arg):
        if self.LOG:
            self.LOG.info(arg)
        else:
            print('[',self.mod_name,'(info)]',arg)

    def warn(self,arg):
        if self.LOG:
            self.LOG.warn(arg)
        else:
            print('[',self.mod_name,'(warm)]',arg)

    def error(self,arg):
        if self.LOG:
            self.LOG.error(arg)
        else:
            print('[',self.mod_name,'(error)]',arg)

    def debug(self,arg):
        if self.LOG:
            self.LOG.debug(arg)
        else:
            print('[',self.mod_name,'(debug)]',arg)

    def exception(self,e):
        if self.LOG:
            self.LOG.exception(e)
        else:
            print('[',self.mod_name,'(exception)]',e)
        if __debug__:
            raise e

def assure_path(path):
    import os.path
    if os.path.isdir(path) is not True:
        os.makedirs(path)

""" 如何判断平台类型
def TestPlatform():
    import platform
    #Windows will be : (32bit, WindowsPE)
    #Linux will be : (32bit, ELF)
    print(platform.architecture())

    #Windows will be : Windows-XP-5.1.2600-SP3 or Windows-post2008Server-6.1.7600
    #Linux will be : Linux-2.6.18-128.el5-i686-with-redhat-5.3-Final
    print(platform.platform())

    #Windows will be : Windows
    #Linux will be : Linux
    print(platform.system())

    #Windows and Linux will be : 3.1.1 or 3.1.3
    print(platform.python_version())

def UsePlatform():
    import platform
    sysstr = platform.system()
    if(sysstr =="Windows"):
        print ("Call Windows tasks")
    elif(sysstr == "Linux"):
        print ("Call Linux tasks")
    else:
        print ("Other System tasks")

"""

def initlog(logfile):
    import logging
    logger = logging.getLogger()
    hdlr = logging.FileHandler(logfile)
    formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)

    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
    console.setFormatter(formatter)
    logger.addHandler(console)

    logger.setLevel(logging.DEBUG)
    return logger


class SynDict(object):
    from threading import Lock
    def __init__(self):
        self._dict = {}
        self._mt = Lock()

    def add(self,k,v):
        self._mt.acquire()
        self._dict[k]=v
        self._mt.release()

    def popitem(self):
        v = None
        self._mt.acquire()
        if len(self._dict) > 0:
            k,v = self._dict.popitem()
        self._mt.release()
        return v

import re
def reg_helper(text,reg_str="",mode=re.I|re.S):
    reg=re.compile(reg_str,mode)
    return reg.findall(text)

class Date2Str:
    FORMATE_SHORT = "%Y-%m-%d %H:%M:%S"
    FORMATE_LONG  = "%Y-%m-%d %H:%M:%S"
    @staticmethod
    def short(time_s):
        from time import strftime
        if time_s is None:
            return "0000-00-00 00:00"
        try:
            return strftime(Date2Str.FORMATE_SHORT,time_s)
        except Exception as e:
            return "0000-00-00 00:00"

    @staticmethod
    def long(time_s):
        from time import strftime
        if time_s is None:
            return "0000-00-00 00:00"
        try:
            return strftime(Date2Str.FORMATE_LONG,time_s)
        except Exception as e:
            return "0000-00-00 00:00"

if __name__ == '__main__':
    import re
    m= re.findall(r'(^\s*$)','74.125.128.103  www.google.com.hk\n',re.MULTILINE)
    #m= re.findall(r'\s+(plus\.google\.com)\s*$','74.125.229.161  plus.google.com\n')
    if m:
        print(m)
    pass

